package com.mmall.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CookieUtil {

    /**
     * private final static String COOKIE_DOMAIN = ".happymmall.com.cn";
     */
    private final static String COOKIE_DOMAIN = "www.tomsmmall.com";
    private final static String COOKIE_NAME = "mmall_login_token";

    /**
     * 读取登陆Token
     * @param request
     * @return
     */
    public static String readLoginToken(HttpServletRequest request){
        Cookie[] cks = request.getCookies();
        if (cks != null){
            for (Cookie ck: cks){
                log.info("read cookieName:{}, cookieValue:{}",ck.getName(), ck.getValue());
                if (StringUtils.equals(ck.getName(), COOKIE_NAME)){
                    log.info("return cookieName:{}, cookieValue:{}",ck.getName(), ck.getValue());
                    return ck.getValue();
                }
            }
        }
        return null;
    }

    /**
     *  记录登陆Token
     * @param response
     * @param token
     */
    public static void writeLoginToken(HttpServletResponse response, String token){

        // 用来种在浏览器的cookie
        Cookie ck = new Cookie(COOKIE_NAME, token);
        ck.setDomain(COOKIE_DOMAIN);
        // 设置在跟目录
        ck.setPath("/");
        // 设置为true表示不能通过脚本访问cookie，防止脚本攻击
        ck.setHttpOnly(true);
        /*
         * 1. 单位（秒）；
         * 2. 不设置的话cookie就不会写入硬盘，只会保存在内存，只对当前页面有效；
         * 负数如 -1代表永久
         */
        ck.setMaxAge(60 * 60 * 24 * 365);
        log.info("write cookieName:{}, cookieValue:{}", ck.getName(), ck.getValue());
        response.addCookie(ck);
    }

    /**
     * 删除Cookie
     * @param request
     * @param response
     */
    public static void delLoginToken(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cks = request.getCookies();
        if (cks != null){
            for (Cookie ck: cks){
                if (StringUtils.equals(ck.getName(), COOKIE_NAME)){
                    ck.setDomain(COOKIE_DOMAIN);
                    ck.setPath("/");
                    // 设置成0代表删除
                    ck.setMaxAge(0);
                    log.info("delete cookieName:{}, cookieValue:{}",ck.getName(), ck.getValue());
                    response.addCookie(ck);
                    return;
                }
            }
        }
    }

}
